package org.laobai.filters;

import io.jsonwebtoken.Claims;
import org.laobai.auth.entity.UserInfo;
import org.laobai.auth.utils.JwtUtils;
import org.laobai.properties.JWTProperties;
import org.laobai.properties.PathProperties;
import org.laobai.utils.JwtUtil;
import org.laobai.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    private static final String AUTHORIZE_TOKEN ="Authorize";

    @Autowired
    private PathProperties pathProperties;

    @Autowired
    private JWTProperties jwtProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 请求上下文
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();

        // 白名单
//        if(path.startsWith("/api/user/login")){
//            return chain.filter(exchange);
//        }
        List<String> whitePaths = pathProperties.getPaths();
        for (String whitePath : whitePaths) {
            if(path.startsWith(whitePath)){
                return chain.filter(exchange);
            }
        }

        //获取jwt串
        // 参数获取
        String token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        if(StringUtils.isEmpty(token)){
            // header获取
            token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);

            if(StringUtils.isEmpty(token)){
                // 从cookie里获取
                HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
                if(Objects.nonNull(cookie)) {
                    token = cookie.getValue();
                }
            }
        }
        // 获取不到，去登录
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 获取到，解析串
        try {
             //Claims claims = JwtUtil.parseJWT(token);
            UserInfo userInfo = JwtUtils.getUserInfo(jwtProperties.getPublicKey(), token);

            request.mutate().header("userInfo",userInfo.toString());
        } catch (Exception e) {
            e.printStackTrace();
            // 解析失败，去登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        // 解析成功，放行
        return chain.filter(exchange);
    }

    // 排序
    @Override
    public int getOrder() {
        return 0;
    }
}
